package com.dutiantech.zimg.utils;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.dutiantech.rambo.exception.RamboRunTimeException;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

public class ZimgClientUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(ZimgClientUtil.class);
	/**
	 * 将图片文件上传到zimg服务器
	 * 
	 * @param url
	 * @param fileName
	 * @param ext
	 * @return
	 */
	public static String Send(String url, String fileName, String ext) {

		StringBuilder respData = new StringBuilder();
		try {
			// 获得connection对象
			URL ul = new URL(url);
			URLConnection connection = ul.openConnection();
			connection.setReadTimeout(50000);
			connection.setConnectTimeout(25000);
			HttpURLConnection uc = (HttpURLConnection) connection;

			// 设置HTTP协议的消息头
			uc.setRequestMethod("POST");
			uc.setRequestProperty("Connection", "Keep-Alive");
			uc.setRequestProperty("Cache-Control", "no-cache");
			uc.setRequestProperty("Content-Type", "image/" + ext);// png,jpg,jpeg
			uc.setDoOutput(true);
			uc.setDoInput(true);

			// 与建立服务器连接
			uc.connect();
			// 设置传输模式为二进制
			OutputStream om = uc.getOutputStream();
			// 循环读取图片，发送到zimg服务器
			FileInputStream in = new FileInputStream(fileName);
			byte[] buf = new byte[8192];
			while (true) {
				int len = in.read(buf);
				if (len <= 0)
					break;
				om.write(buf, 0, len);
			}

			// 到开输入（返回信息）流
			InputStreamReader im = new InputStreamReader(uc.getInputStream(), "UTF-8");
			// 循环读取，直到结束，获取返回信息
			char[] bb = new char[8192];
			while (true) {
				int length = im.read(bb);
				if (length == -1)
					break;
				char[] bc = new char[length];
				for (int i = 0; i < length; i++)
					bc[i] = bb[i];
				String tynData = new String(bc);
				if(StringUtils.isNotEmpty(tynData)) {
					respData.append(tynData);
				}
			}
			logger.info("zimg 返回数据 ：" + respData);
			// 关闭上下行
			im.close();
			uc.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RamboRunTimeException("zimg上传图片失败");
		}

		return respData.toString();
	}
	
	public static void main(String[] args) {
		String url = "http://123.56.90.180:8000";
		String respData = Send(url, "E:/hsd.png", "png");
//		String ext = "E:/hsd.png".substring("E:/hsd.png".lastIndexOf(".")+1);
		System.out.println(respData);
        JSONObject result = JSONObject.parseObject(respData);
    	
//    	{"ret":true,"info":{"md5":"42b0bfda506dd4f9be66f1971225fffd","size":700}}
    	String ret = result.getString("ret");
    	String info = result.getString("info");
    	
    	if("true".equals(ret))
    		System.out.println(ret);
    	JSONObject infoData = JSONObject.parseObject(info);
    	String md5 = infoData.getString("md5");
    	System.out.println(md5);
	}
}
